<?php

namespace common\modules\sms\models\frontend;

use common\CMS;
use Yii;
use yii\web\ForbiddenHttpException;

class Customer extends \common\modules\sms\models\Customer
{

    /**
     * @var static
     */
    public static $current;

    /**
     * 检查签名信息
     *
     * @throws \yii\web\ForbiddenHttpException
     */
    public static function checkSignature()
    {
        $time = (int) Yii::$app->request->get('time');
        if ( ! $time)
        {
            throw new ForbiddenHttpException('缺少time参数');
        }
        // 如果时间相差太多,那就当做是无效时间
        if (abs(time() - $time) > 60 * 3)
        {
            throw new ForbiddenHttpException('time参数过期');
        }

        $sign = (string) Yii::$app->request->get('sign');
        if ( ! $time)
        {
            throw new ForbiddenHttpException('缺少sign参数');
        }

        $appID = Yii::$app->request->get('app_id');
        if ( ! $appID)
        {
            throw new ForbiddenHttpException('缺少app_id参数');
        }

        /** @var self $customer */
        $customer = self::findOne([
            'app_id' => $appID,
        ]);
        if ( ! $customer)
        {
            throw new ForbiddenHttpException('app_id参数错误');
        }

        $uri = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
        $requestSign = CMS::generateSign('sms-api', $uri, [
            'app_id' => $appID,
            'time' => $time
        ], $customer->app_secret);
        // sign对不上
        if ($requestSign !== $sign)
        {
            throw new ForbiddenHttpException('签名错误');
        }

        if ($customer->quota_used >= $customer->quota_total)
        {
            throw new ForbiddenHttpException('使用额度已到达上限');
        }

        self::$current = $customer;
    }
}
